import React, { useState, useEffect, useRef } from "react";
import userApi from "../../../service/api/user";
import roleApi from "../../../service/api/role";
import regionApi from "../../../service/api/region";
import UserForm from "./components/UserForm";
import { Table, Space, Button, Modal, message, Tag, Switch } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";

const { confirm } = Modal;

export default function UserList() {
  const [dataSource, setDataSource] = useState();
  const [roleList, setRoleList] = useState([]);
  const [regionList, setRegionList] = useState([]);
  useEffect(() => {
    fetchDate();
    fetchRoleList();
    fetchRegionList();
    // eslint-disable-next-line
  }, []);

  const roleObj = {
    1: "superAdmin",
    2: "admin",
    3: "editor",
  };
  const { roleId, username, region } = JSON.parse(localStorage.getItem("user"));

  const fetchDate = async () => {
    const data = await userApi.list({
      _expand: "role",
    });
    console.log(data);
    setDataSource(
      roleObj[roleId] === "superAdmin"
        ? data
        : [
            ...data.filter((item) => item.username === username),
            ...data.filter(
              (item) =>
                item.region === region && roleObj[item.roleId] === "editor"
            ),
          ]
    );
  };

  const fetchRoleList = async () => {
    const data = await roleApi.list();
    console.log(data);
    setRoleList(data);
  };

  const fetchRegionList = async () => {
    const data = await regionApi.list();
    console.log(data);
    setRegionList(data);
  };

  // 删除
  const deleteMethod = (item) => {
    console.log(item);
    const fetchDdlDate = async () => {
      const res = await userApi.del(item.id);
      if (res.status === 200) {
        fetchDate();
        message.success("删除成功");
      }
    };
    fetchDdlDate();
  };

  // 新增
  const addMethod = async () => {
    try {
      const formData = await addForm.current.validateFields();
      console.log("校验成功");
      const res = await userApi.create({
        ...formData,
        roleState: true,
        default: false,
      });
      if (res.status === 201) {
        fetchDate();
        addForm.current.resetFields();
        message.success("保存成功");
        setIsModalVisible(false);
      }
    } catch (error) {
      console.log(error);
    }
  };

  // 修改
  const editMethod = async () => {
    try {
      const formData = await editForm.current.validateFields();
      const res = await userApi.update(currentUser.id, formData);
      if (res.status === 200) {
        fetchDate();
        message.success("修改成功！");
        setUpdateModalVisible(false);
      }
    } catch (error) {
      console.log(error);
    }
  };

  // 状态切换
  const [loading, setLoading] = useState(false);
  const switchChange = async (item) => {
    item.roleState = !item.roleState;
    setLoading(true);
    const res = await userApi.update(item.id, {
      roleState: item.roleState,
    });
    if (res.status === 200) {
      setDataSource([...dataSource]);
      setLoading(false);
    }
    console.log(item);
  };

  const delConfirm = (item) => {
    confirm({
      title: "提示",
      icon: <ExclamationCircleOutlined />,
      content: "确定要删除吗？",
      okText: "确认",
      cancelText: "取消",
      onOk() {
        console.log("OK");
        deleteMethod(item);
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
    },
    {
      title: "区域",
      dataIndex: "region",
      filters: [
        {
          text: "全球",
          value: "",
        },
        ...regionList.map((item) => ({
          text: item.title,
          value: item.value,
        })),
      ],
      onFilter: (value, item) => item.region === value,
      render: (region) => {
        return <b>{region ? region : "全球"}</b>;
      },
    },
    {
      title: "用户名",
      dataIndex: "username",
      render: (username) => {
        return <Tag color="orange">{username}</Tag>;
      },
    },
    {
      title: "角色名称",
      dataIndex: "role",
      render: (role) => {
        return role.roleName;
      },
    },
    {
      title: "用户状态",
      dataIndex: "roleState",
      render: (roleState, item) => {
        return (
          <Switch
            checked={roleState}
            disabled={item.default}
            loading={loading}
            onChange={() => switchChange(item)}
          ></Switch>
        );
      },
    },
    {
      title: "操作",
      key: "action",
      render: (item) => (
        <Space size="middle">
          <Button
            type="primary"
            size="small"
            ghost
            disabled={item.default}
            onClick={() => openEditUser(item)}
          >
            编辑
          </Button>
          <Button
            type="primary"
            size="small"
            danger
            ghost
            disabled={item.default}
            onClick={() => delConfirm(item)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [updateModalVisible, setUpdateModalVisible] = useState(false);
  const [currentUser, setCurrentUser] = useState({});

  const [updateDisable, setUpdateDisable] = useState(false);
  const openEditUser = (item) => {
    setCurrentUser(item);
    // 更新时表单并未生成 需要改成异步
    setTimeout(() => {
      setUpdateModalVisible(true);
      if (item.roleId === 1) {
        // 禁用
        setUpdateDisable(true);
      } else {
        setUpdateDisable(false);
      }
      editForm.current.setFieldsValue(item);
    }, 0);
  };

  const addForm = useRef(null);
  const editForm = useRef(null);

  return (
    <>
      <div style={{ marginBottom: 10 }}>
        <Button
          type="primary"
          onClick={() => {
            setIsModalVisible(true);
          }}
        >
          添加用户
        </Button>
      </div>
      <Table
        bordered
        dataSource={dataSource}
        columns={columns}
        rowKey={(item) => item.id}
        pagination={{ pageSize: 20 }}
        size="small"
      />
      {/* 编辑用户弹窗 */}
      <Modal
        title="修改用户"
        okText="更新"
        cancelText="取消"
        isUpdate={true}
        visible={updateModalVisible}
        onOk={editMethod}
        onCancel={() => {
          setUpdateModalVisible(false);
          // 关闭弹窗时刷新 updateDisable
          setUpdateDisable(!updateDisable);
        }}
      >
        <UserForm
          ref={editForm}
          regionList={regionList}
          roleList={roleList}
          updateDisable={updateDisable}
        ></UserForm>
      </Modal>
      {/* 新增用户弹窗 */}
      <Modal
        title="添加用户"
        okText="保存"
        cancelText="取消"
        visible={isModalVisible}
        onOk={addMethod}
        onCancel={() => setIsModalVisible(false)}
      >
        <UserForm
          ref={addForm}
          regionList={regionList}
          roleList={roleList}
        ></UserForm>
      </Modal>
    </>
  );
}
